import { reqLogin, reqGetUserInfo } from '@/api/user'

//创建用户相关的仓库
import { defineStore } from 'pinia'
//引入类型
import { loginForm, loginRes } from '@/api/user/type'
import { UserState } from './types'

//引入token工具类
import { setToken, getToken, removeToken } from '@/utils/token'

//引入menu
import { constRouter } from '@/router/routers'

const useUserStore = defineStore('User', {
  //小仓库存储数据地方
  state: (): UserState => {
    return {
      token: getToken(),
      userInfo: null,
      menuRouters: constRouter,
    }
  },
  //定义方法 异步/逻辑地方
  actions: {
    async userLogin(data: loginForm) {
      //请求登录接口
      const res: loginRes = await reqLogin(data)
      //请求成功后将数据存到小仓库中
      if (res.code === 200) {
        this.token = res.data.token as string
        setToken(this.token)
        return 'success'
      } else {
        // 断言
        return Promise.reject(new Error(res.data.message))
      }
    },
    async getUserInfo() {
      //请求用户信息接口
      if (!this.token) {
        return Promise.reject(new Error('请先登录'))
      }
      const res: any = await reqGetUserInfo()
      if (res.code === 200) {
        this.userInfo = res.data.checkUser
        return 'success'
      } else {
        // 断言
        return Promise.reject(new Error(res.data.message))
      }
    },
    logOut() {
      this.token = null
      this.userInfo = null
      removeToken()
    },
  },
  getters: {},
})

//对外暴露小仓库
export default useUserStore
